<template>
  <div>
    <div class="tabBar">
      <div
        v-for="(item, index) in tabList"
        :key="index"
        class="tabItem"
        @click="getCommodity(index + 1)"
      >
        <div :class="{ active: item.active }">{{ item.title }}</div>
        <div :class="{ line: item.active }"></div>
      </div>
    </div>
    <slot name="content"></slot>
  </div>
</template>

<script>
export default {
  props: {
    tabList: {
      type: Array,
      default: [],
    },
  },
  mounted() {
    this.tabList[0].active = true;
    this.$emit("getCommodity", 1);
    window.addEventListener("scroll", this.listenScroll);
  },
  unmounted() {
    window.removeEventListener("scroll", this.listenScroll);
  },
  methods: {
    listenScroll() {
      const tabBar = document.querySelector(".tabBar");
      const scrollTop = window.scrollY;
      const tabBarTop = tabBar.getBoundingClientRect().top;
      if (scrollTop > tabBarTop) {
        tabBar.style.position = "fixed";
        tabBar.style.top = "0";
        tabBar.style.zIndex = "999";
        tabBar.style.width = "100%";
      } else {
        tabBar.style.position = "relative";
        tabBar.style.top = "auto";
        tabBar.style.zIndex = "auto";
      }
    },
    getCommodity(index) {
      this.tabList.forEach((item) => {
        item.active = false;
      });
      this.tabList[index - 1].active = true;
      this.$emit("getCommodity", index);
    },
  },
};
</script>

<style scoped lang="scss">
.line {
  width: 33%;
  height: 1px;
  background-color: #39d81f;
  margin: auto;
  border-radius: 1.333vw;
  -webkit-transform: translateY(1.333vw);
  -moz-transform: translateY(1.333vw);
  -ms-transform: translateY(1.333vw);
  -o-transform: translateY(1.333vw);
  transform: translateY(1.333vw);
}
.active {
  color: #39d81f !important;
}
.tabItem {
  width: 17.6vw;
}
// .tabItem:active {
//   background-color: #39d81f;
//   height: 13.333vw;
//   line-height: 13.333vw;
//   text-align: center;
//   color: #39d81f !important;
// }
.tabBar {
  box-sizing: border-box;
  display: flex;
  justify-content: space-around;
  margin: 1.333333vw 2.667vw;
  padding: 2.667vw 0;
  font-size: 3.733vw;
  font-weight: bold;
  background-color: #fff;
  border-radius: 4vw;
  height: 13.333vw;
  align-items: center;
}
</style>
